package com.ruoyi.chat.userController;

import com.cyl.h5.config.SecurityUtil;
import com.ruoyi.chat.domain.FhChatFriend;
import com.ruoyi.chat.domain.FhInfoUserDto;
import com.ruoyi.chat.domain.UserHomeDto;
import com.ruoyi.chat.service.IFhChatFriendService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.index.domain.FhIndexPostinfo;
import com.ruoyi.index.service.IFhIndexPostinfoService;
import com.ruoyi.info.domain.FhInfoCatchrecord;
import com.ruoyi.info.domain.FhInfoUser;
import com.ruoyi.info.domain.FhInfoUsertask;
import com.ruoyi.info.service.IFhInfoCatchrecordService;
import com.ruoyi.info.service.IFhInfoUserService;
import com.ruoyi.info.service.IFhInfoUsertaskService;
import com.ruoyi.tokenTools.UserLoginToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 好友Controller
 *
 * @author ruoyi
 * @date 2024-11-11
 */
@Api(tags = "聊天好友接口")
@RestController
@RequestMapping("/app/chat/friend")
public class UserFhChatFriendController extends BaseController
{
    @Autowired
    private IFhChatFriendService fhChatFriendService;

    @Autowired
    private IFhInfoUserService iFhInfoUserService;

    @Autowired
    private IFhInfoUsertaskService iFhInfoUsertaskService;

    @Autowired
    private IFhInfoCatchrecordService iFhInfoCatchrecordService;

    @Autowired
    private IFhIndexPostinfoService iFhIndexPostinfoService;

    /**
     * 获取推荐朋友列表
     */
    @UserLoginToken
    @ApiOperation("获取推荐朋友列表")
    @GetMapping("/referFriendList")
    public R<List<FhInfoUserDto>> referFriendList()
    {
        try {
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            //如果有用户关注了我，我没关注别人，则为推荐朋友
            FhChatFriend fhChatFriend = new FhChatFriend();
            //粉丝列表（关注我的用户）
            fhChatFriend.setFriendId(userId);
            List<FhChatFriend> fansList = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            //好友列表（我关注的用户）
            fhChatFriend.setUserId(userId);
            List<FhChatFriend> friendList = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            //推荐好友列表
            List<FhChatFriend> referFriendList = new ArrayList<>();
            //推荐好友userIdList
            ArrayList<Long> userIdList = new ArrayList<>();
            for (int i = 0; i < fansList.size(); i++) {
                //粉丝id
                Long fansUserId = fansList.get(i).getUserId();
                boolean flag = true;
                for (int j = 0; j < friendList.size(); j++) {
                    if(friendList.get(j).getFriendId()==fansUserId){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    referFriendList.add(fansList.get(i));
                    userIdList.add(fansList.get(i).getUserId());
                }
            }
            //查询推荐好友信息及关注他的用户的一个好友名
            List<FhInfoUserDto> fhInfoUserDtos;
            if (userIdList.isEmpty()) {
                // 如果没有推荐好友，返回空列表而不是执行错误的SQL
                fhInfoUserDtos = new ArrayList<>();
            } else {
                fhInfoUserDtos = iFhInfoUserService.selectFhInfoUserAndFriendNameListByUserIds(userIdList);
            }

            return R.ok(fhInfoUserDtos);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 搜索好友
     */
    @UserLoginToken
    @ApiOperation("搜索好友")
    @GetMapping("/selectFriendByName")
    public R<List<FhInfoUserDto>> selectFrient(String name)
    {
        try{
            List<FhInfoUserDto> fhInfoUserDtoList = new ArrayList<>();

            Long userId = SecurityUtil.getLocalUserInfo().getId();
            FhInfoUser fhInfoUser = new FhInfoUser();
            fhInfoUser.setName(name);
            List<FhInfoUser> fhInfoUsers = iFhInfoUserService.selectFhInfoUserList(fhInfoUser);
            //去除掉已关注的好友
            List<FhChatFriend> fhChatFriendList = fhChatFriendService.selectFhChatFriendByUserId(userId);
            for (int i = 0; i < fhInfoUsers.size(); i++) {
                Boolean flag = true;
                for (int j = 0; j < fhChatFriendList.size(); j++) {
                    if(Objects.equals(fhInfoUsers.get(i).getUserId(), fhChatFriendList.get(j).getFriendId())){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    FhInfoUserDto fhInfoUserDto = new FhInfoUserDto();
                    BeanUtils.copyProperties(fhInfoUsers.get(i), fhInfoUserDto);
                    fhInfoUserDto.setFollower(false);
                    fhInfoUserDtoList.add(fhInfoUserDto);
                }else {
                    FhInfoUserDto fhInfoUserDto = new FhInfoUserDto();
                    BeanUtils.copyProperties(fhInfoUsers.get(i), fhInfoUserDto);
                    fhInfoUserDto.setFollower(true);
                    fhInfoUserDtoList.add(fhInfoUserDto);
                }
            }
            return R.ok(fhInfoUserDtoList);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
    }

    /**
     * 根据通讯录获取朋友列表
     */
    @UserLoginToken
    @ApiOperation("根据通讯录获取朋友列表")
    @GetMapping("/friendListByPhoneList")
    public  R<List<FhInfoUser>> friendListByPhoneList(String phoneList)
    {
        try {
            List<FhInfoUser> fhInfoUsersVo = new ArrayList<>();

            Long userId = SecurityUtil.getLocalUserInfo().getId();
            String[] phoneListValue = phoneList.split(",");
            FhInfoUser fhInfoUser = new FhInfoUser();
            //根据通讯录获取朋友列表
            List<FhInfoUser> friendListByPhoneList = new ArrayList<>();
            for (int i = 0; i < phoneListValue.length; i++) {
                fhInfoUser.setPhone(phoneListValue[i]);
                List<FhInfoUser> fhInfoUsers = iFhInfoUserService.selectFhInfoUserList(fhInfoUser);
                if(!fhInfoUsers.isEmpty()){
                    friendListByPhoneList.add(fhInfoUsers.get(0));
                }
            }
            //去除掉已关注的好友
            List<FhChatFriend> fhChatFriendList = fhChatFriendService.selectFhChatFriendByUserId(userId);
            for (int i = 0; i < friendListByPhoneList.size(); i++) {
                Boolean flag = true;
                for (int j = 0; j < fhChatFriendList.size(); j++) {
                    if(Objects.equals(friendListByPhoneList.get(i).getUserId(), fhChatFriendList.get(j).getFriendId())){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    fhInfoUsersVo.add(friendListByPhoneList.get(i));
                }
            }

            return R.ok(fhInfoUsersVo);
        }catch (Exception e){
            return R.fail();
        }

    }


    /**
     * 关注好友
     */
    @UserLoginToken
    @ApiOperation("关注好友")
    @Log(title = "好友", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public R<String> add(Long friendId)
    {
        try {
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            //判断是否已经关注
            FhChatFriend fhChatFriend1 = new FhChatFriend();
            fhChatFriend1.setUserId(userId);
            fhChatFriend1.setFriendId(friendId);
            List<FhChatFriend> fhChatFriends1 = fhChatFriendService.selectFhChatFriendList(fhChatFriend1);
            if(!fhChatFriends1.isEmpty()){
                return R.fail("已经关注，请勿重复关注");
            }
            FhInfoUser fhInfoUser = new FhInfoUser();
            //修改用户信息的关注数
            fhInfoUser.setUserId(userId);
            List<FhInfoUser> fhInfoUsers = iFhInfoUserService.selectFhInfoUserList(fhInfoUser);
            Long followers = fhInfoUsers.get(0).getFollowers();
            followers+=1;
            fhInfoUsers.get(0).setFollowers(followers);
            iFhInfoUserService.updateFhInfoUser(fhInfoUsers.get(0));
            //修改用户信息的粉丝数
            fhInfoUser.setUserId(friendId);
            List<FhInfoUser> fhInfoUsers1 = iFhInfoUserService.selectFhInfoUserList(fhInfoUser);
            Long fans = fhInfoUsers1.get(0).getFans();
            fans+=1;
            fhInfoUsers1.get(0).setFans(fans);
            iFhInfoUserService.updateFhInfoUser(fhInfoUsers1.get(0));
            //关注该用户
            FhInfoUser fhInfoUserFriend = iFhInfoUserService.selectFhInfoUserByUserId(friendId);
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(userId);
            fhChatFriend.setFriendAdress(fhInfoUserFriend.getAddress());
            fhChatFriend.setFriendImage(fhInfoUserFriend.getImage());
            fhChatFriend.setFriendName(fhInfoUserFriend.getName());
            fhChatFriend.setFriendId(friendId);
            fhChatFriend.setCrateTime(new Date());
            fhChatFriend.setFriendPhone(fhInfoUserFriend.getPhone());

            fhChatFriendService.insertFhChatFriend(fhChatFriend);

            //修改添加好友任务完成状态
            //compleTask(2L);

            // 插入添加好友任务日志（任务ID 2：添加好友）
            try {
                iFhInfoUsertaskService.insertTaskLog(userId, 2L);
            } catch (Exception e) {
                System.out.println("插入添加好友任务日志失败: " + e.getMessage());
            }

            return R.ok("关注成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.fail(e.getMessage());
        }
    }

    /**
     * 用户完成任务加积分
     */
    public R<String> compleTask(Long taskId)
    {
        try {
            //修改信息表
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            FhInfoUser fhInfoUserInfo = iFhInfoUserService.selectFhInfoUserByUserId(userId);
            Long points = fhInfoUserInfo.getPoints();
            points+=10;
            fhInfoUserInfo.setPoints(points);
            iFhInfoUserService.updateFhInfoUser(fhInfoUserInfo);
            //修改任务表状态，1为未完成，0为完成
            FhInfoUsertask fhInfoUsertask = new FhInfoUsertask();
            fhInfoUsertask.setUserId(userId);
            fhInfoUsertask.setTaskId(taskId);
            fhInfoUsertask.setCompletionStatus("0");
            iFhInfoUsertaskService.updateFhInfoUsertaskByUserIdAndTaskId(fhInfoUsertask);
            return R.ok("完成成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    /**
     * 取消关注好友
     */
    @UserLoginToken
    @ApiOperation("取消关注好友")
    @Log(title = "好友", businessType = BusinessType.DELETE)
    @DeleteMapping()
    public R<String> remove(Long friendId)
    {
        try {
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            FhInfoUser fhInfoUser = new FhInfoUser();
            //判断是否已经关注
            FhChatFriend fhChatFriend1 = new FhChatFriend();
            fhChatFriend1.setUserId(userId);
            fhChatFriend1.setFriendId(friendId);
            List<FhChatFriend> fhChatFriends1 = fhChatFriendService.selectFhChatFriendList(fhChatFriend1);
            if(fhChatFriends1.isEmpty()){
                return R.fail("未关注，无法取消关注");
            }
            //修改用户信息的关注数
            fhInfoUser.setUserId(userId);
            List<FhInfoUser> fhInfoUsers = iFhInfoUserService.selectFhInfoUserList(fhInfoUser);
            Long followers = fhInfoUsers.get(0).getFollowers();
            followers-=1;
            fhInfoUsers.get(0).setFollowers(followers);
            iFhInfoUserService.updateFhInfoUser(fhInfoUsers.get(0));
            //修改用户信息的粉丝数
            fhInfoUser.setUserId(friendId);
            List<FhInfoUser> fhInfoUsers1 = iFhInfoUserService.selectFhInfoUserList(fhInfoUser);
            Long fans = fhInfoUsers1.get(0).getFans();
            fans-=1;
            fhInfoUsers1.get(0).setFans(fans);
            iFhInfoUserService.updateFhInfoUser(fhInfoUsers1.get(0));
            //取消关注该用户
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(userId);
            fhChatFriend.setFriendId(friendId);
            List<FhChatFriend> fhChatFriends = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            fhChatFriendService.deleteFhChatFriendById(fhChatFriends.get(0).getId());

            return R.ok("取消关注成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.fail(e.getMessage());
        }
    }

    /**
     * 查询好友列表
     */
    @UserLoginToken
    @ApiOperation("关注列表，粉丝列表")
    @GetMapping("/list")
    @Transactional
    public R<TableDataInfo> list(
            @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize",defaultValue = "10") int pageSize,
            Long userId,String listType,String searchName
    )
    {
        try {
            List<FhInfoUserDto> fhInfoUserDtoList = new ArrayList<>();
            //登录用户的好友列表
            Long id = SecurityUtil.getLocalUserInfo().getId();
            List<FhChatFriend> friendListByLoginId = fhChatFriendService.selectFhChatFriendByUserId(id);
            /**
             * listType 1:关注列表  2:粉丝列表
             */
            if(listType.equals("1")){
                //根据传入用户id获取的好友列表
                startPage();
                List<FhChatFriend> list = fhChatFriendService.selectFhChatFriendByUserId(userId);
                if (list == null) {
                    return R.ok(getDataTable(new ArrayList<>())); // 返回空数据
                }
                // 检查列表是否包含有效数据
                if (list.stream().anyMatch(friend -> friend.getFriendId() == null)) {
                    return R.fail("好友数据异常，包含空的friendId");
                }
                long[] userIds = new long[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    userIds[i] = list.get(i).getFriendId();
                }
                // 如果没有用户ID，直接返回空列表，防止SQL语法错误
                if (userIds.length == 0) {
                    return R.ok(getDataTable(fhInfoUserDtoList)); // 返回空数据
                }
                //关注列表的用户信息列表
                List<FhInfoUser> fhInfoUserList = iFhInfoUserService.selectFhInfoUserListByUserIds(userIds);
                for (FhInfoUser fhInfoUser : fhInfoUserList) {
                    FhInfoUserDto fhInfoUserDto = new FhInfoUserDto();
                    fhInfoUserDto.setUserId(fhInfoUser.getUserId());
                    fhInfoUserDto.setImage(fhInfoUser.getImage());
                    fhInfoUserDto.setName(fhInfoUser.getName());
                    //fhInfoUserDto.setFans(fhInfoUser.getFans());
                    //判断是否关注
//                    boolean isFollower = friendListByLoginId.stream().anyMatch(friend ->friend.getFriendId().equals(fhInfoUser.getUserId()));
                    fhInfoUserDto.setFollower(true);
                    //粉丝名
                    FhChatFriend fhChatFriend = new FhChatFriend();
                    fhChatFriend.setFriendId(fhInfoUser.getUserId());
                    List<FhChatFriend> fhChatFriends = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
                    if(fhChatFriends!=null&& !fhChatFriends.isEmpty()){
                        FhInfoUser fhInfoUser1 = iFhInfoUserService.selectFhInfoUserByUserId(fhChatFriends.get(0).getUserId());
                        if (fhInfoUser1 != null) {
                            fhInfoUserDto.setFans((long) fhChatFriends.size());
                            fhInfoUserDto.setFansName(fhInfoUser1.getName());
                        }
                    }
                    fhInfoUserDtoList.add(fhInfoUserDto);
                }
            }else {
                //根据传入用户id获取的粉丝列表
                FhChatFriend fhChatFriend1 = new FhChatFriend();
                fhChatFriend1.setFriendId(userId);
                startPage();
                List<FhChatFriend> list = fhChatFriendService.selectFhChatFriendList(fhChatFriend1);
                if (list == null) {
                    return R.ok(getDataTable(new ArrayList<>())); // 返回空数据
                }
                long[] userIds = new long[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    userIds[i] = list.get(i).getUserId();
                }
                // 如果没有用户ID，直接返回空列表，防止SQL语法错误
                if (userIds.length == 0) {
                    return R.ok(getDataTable(fhInfoUserDtoList)); // 返回空数据
                }
                //粉丝列表的用户信息列表
                List<FhInfoUser> fhInfoUserList = iFhInfoUserService.selectFhInfoUserListByUserIds(userIds);
                for (FhInfoUser fhInfoUser : fhInfoUserList) {
                    FhInfoUserDto fhInfoUserDto = new FhInfoUserDto();
                    fhInfoUserDto.setUserId(fhInfoUser.getUserId());
                    fhInfoUserDto.setImage(fhInfoUser.getImage());
                    fhInfoUserDto.setName(fhInfoUser.getName());
                    //fhInfoUserDto.setFans(fhInfoUser.getFans());
                    //判断是否关注
                    boolean isFollower = friendListByLoginId.stream().anyMatch(friend ->friend.getFriendId().equals(fhInfoUser.getUserId()));
                    fhInfoUserDto.setFollower(isFollower);
                    //粉丝名
                    FhChatFriend fhChatFriend = new FhChatFriend();
                    fhChatFriend.setFriendId(fhInfoUser.getUserId());
                    List<FhChatFriend> fhChatFriends = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
                    if (fhChatFriends != null && !fhChatFriends.isEmpty()) {
                        fhChatFriends.stream().findFirst().ifPresent(firstFriend -> {
                            FhInfoUser fhInfoUser1 = iFhInfoUserService.selectFhInfoUserByUserId(firstFriend.getUserId());
                            if (fhInfoUser1 != null) {
                                fhInfoUserDto.setFans((long) fhChatFriends.size());
                                fhInfoUserDto.setFansName(fhInfoUser1.getName());
                            }
                        });
                    } else {
                        // 可选：设置默认值或跳过
                        fhInfoUserDto.setFansName(null);
                        fhInfoUserDto.setFans(0L);
                    }
                    fhInfoUserDtoList.add(fhInfoUserDto);
                }
            }
            //根据搜索名筛选列表
            if(searchName!=null&&!searchName.isEmpty()){
                List<FhInfoUserDto> filteredList = new ArrayList<>();
                for (FhInfoUserDto fhInfoUserDto : fhInfoUserDtoList) {
                    if (fhInfoUserDto.getName().contains(searchName)) {
                        filteredList.add(fhInfoUserDto);
                    }
                }
                return R.ok(getDataTable(filteredList));
            }
            return R.ok(getDataTable(fhInfoUserDtoList));
        }catch (Exception e){
            logger.error("查询好友列表异常: userId={}, listType={}, searchName={}", userId, listType, searchName, e);
            String errorMsg = e.getMessage();
            if (errorMsg == null || errorMsg.isEmpty()) {
                errorMsg = "系统内部错误";
            }
            return R.fail("查询好友列表失败: " + errorMsg);
        }
    }

    /**
     * 获取用户主页
     */
    @UserLoginToken
    @ApiOperation("用户主页")
    @GetMapping(value = "/{userId}")
    public R<UserHomeDto> getUserHome(@PathVariable("userId") Long userId)
    {
        try {
            Long id = SecurityUtil.getLocalUserInfo().getId();
            //查询是否关注
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(id);
            fhChatFriend.setFriendId(userId);
            List<FhChatFriend> fhChatFriends = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            boolean isFollower = false;
            if(!fhChatFriends.isEmpty()){
                isFollower = true;
            }
            FhInfoUser fhInfoUser = iFhInfoUserService.selectFhInfoUserByUserId(userId);
            FhInfoCatchrecord fhInfoCatchrecord = iFhInfoCatchrecordService.selectFhInfoCatchrecordByUserId(userId);
            return R.ok(new UserHomeDto(isFollower,fhInfoUser,fhInfoCatchrecord));
        }catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取用户主页发布信息
     */
    @UserLoginToken
    @ApiOperation("用户主页发布信息")
    @GetMapping("/post")
    public R<TableDataInfo> getUserHome(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
            Long userId,String sort)
    {
       try {
           // sort == 1：时间从远到近，2：时间从近到远，3：点赞数从高到低，4：点赞数从低到高
           List<FhIndexPostinfo> fhIndexPostinfoList = new ArrayList<>();
           if(sort==null){
               sort = "1";
           }
           startPage();
           if(sort.equals("1")){
               fhIndexPostinfoList = iFhIndexPostinfoService.selectFhIndexPostinfoListSort(userId,"post_time","ASC");
           }else if(sort.equals("2")){
               fhIndexPostinfoList = iFhIndexPostinfoService.selectFhIndexPostinfoListSort(userId,"post_time","DESC");
           }else if(sort.equals("3")){
               fhIndexPostinfoList = iFhIndexPostinfoService.selectFhIndexPostinfoListSort(userId,"likes","ASC");
           }else if(sort.equals("4")){
               fhIndexPostinfoList = iFhIndexPostinfoService.selectFhIndexPostinfoListSort(userId,"likes","DESC");
           }
           return R.ok(getDataTable(fhIndexPostinfoList));
       }catch (Exception e) {
           return R.fail(e.getMessage());
       }
    }


    /**
     * 关注好友(新)
     */
    @UserLoginToken
    @ApiOperation("关注好友(新)")
    @Log(title = "好友", businessType = BusinessType.INSERT)
    @PostMapping("/attention")
    @Transactional
    public R<String> attention(Long friendId) {
        try {
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            //判断是否已经关注
            FhChatFriend fhChatFriend1 = new FhChatFriend();
            fhChatFriend1.setUserId(userId);
            fhChatFriend1.setFriendId(friendId);
            List<FhChatFriend> fhChatFriends1 = fhChatFriendService.selectFhChatFriendList(fhChatFriend1);
            if (!fhChatFriends1.isEmpty()) {
                return R.fail("已经关注，请勿重复关注");
            }
            //关注该用户
            FhInfoUser fhInfoUserFriend = iFhInfoUserService.selectFhInfoUserByUserId(friendId);
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(userId);
            fhChatFriend.setFriendAdress(fhInfoUserFriend.getAddress());
            fhChatFriend.setFriendImage(fhInfoUserFriend.getImage());
            fhChatFriend.setFriendName(fhInfoUserFriend.getName());
            fhChatFriend.setFriendId(friendId);
            fhChatFriend.setCrateTime(new Date());
            fhChatFriend.setFriendPhone(fhInfoUserFriend.getPhone());

            fhChatFriendService.insertFhChatFriend(fhChatFriend);
            return R.ok("关注成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.fail(e.getMessage());
        }
    }

    /**
     * 取消关注好友(新)
     */
    @UserLoginToken
    @ApiOperation("取消关注好友(新)")
    @Log(title = "好友", businessType = BusinessType.DELETE)
    @DeleteMapping("/attention/{friendId}")
    public R<String> callAttention(Long friendId) {
        try {
            Long userId = SecurityUtil.getLocalUserInfo().getId();
            //判断是否已经关注
            FhChatFriend fhChatFriend1 = new FhChatFriend();
            fhChatFriend1.setUserId(userId);
            fhChatFriend1.setFriendId(friendId);
            List<FhChatFriend> fhChatFriends1 = fhChatFriendService.selectFhChatFriendList(fhChatFriend1);
            if (fhChatFriends1.isEmpty()) {
                return R.fail("未关注，无法取消关注");
            }
            //取消关注该用户
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(userId);
            fhChatFriend.setFriendId(friendId);
            List<FhChatFriend> fhChatFriends = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            fhChatFriendService.deleteFhChatFriendById(fhChatFriends.get(0).getId());

            return R.ok("取消关注成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.fail(e.getMessage());
        }
    }


    /**
     * 获取用户主页(新)
     */
    @UserLoginToken
    @ApiOperation("用户主页(新)")
    @GetMapping(value = "/home/{userId}")
    public R<UserHomeDto> userHome(@PathVariable("userId") Long userId) {
        try {
            Long id = SecurityUtil.getLocalUserInfo().getId();
            //查询是否关注
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(id);
            fhChatFriend.setFriendId(userId);
            List<FhChatFriend> fhChatFriends = fhChatFriendService.selectFhChatFriendList(fhChatFriend);
            boolean isFollower = false;
            if (!fhChatFriends.isEmpty()) {
                isFollower = true;
            }
            FhInfoUser fhInfoUser = iFhInfoUserService.selectFhInfoUserByUserId(userId);
            //查询粉丝数
            FhChatFriend fh = new FhChatFriend();
            fh.setFriendId(userId);
            List<FhChatFriend> fhChatFriends1 = fhChatFriendService.selectFhChatFriendList(fh);
            fhInfoUser.setFans((long) fhChatFriends1.size());
            //查询关注数
            List<FhChatFriend> friends = fhChatFriendService.selectFhChatFriendByUserId(userId);
            fhInfoUser.setFollowers((long) friends.size());

            FhInfoCatchrecord fhInfoCatchrecord = iFhInfoCatchrecordService.selectFhInfoCatchrecordByUserId(userId);
            return R.ok(new UserHomeDto(isFollower, fhInfoUser, fhInfoCatchrecord));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


}
